import json


class AssertCheck(object):
    """封装断言解析器"""
    def __init__(self, response): # 私有属性
        self.response = response

    def json_check_key(self,check_key):
        """
        判断json的键key是否存在
        检查json类型的响应body中是否包含一个或多个key
        :param check_key:检查数据字符串
        :return:都包含则返回True； 有一个不包含就返回False
        """
        key_list = check_key.split(',')
        result_list = []  # 放每次比较的结果
        wrong_result = []  #存放比较失败key
        for i in key_list:
            if i in self.response.key():
                result_list.append(True)
            else:
                wrong_result.append(False)
                wrong_result.append(i)
        if False in wrong_result:
            msg = "json的key不正确,不正确的是{}",format(wrong_result)
            print(msg)

        else:
            msg = "json的key全部正确"
            print(msg)
            return True

    def key_value_check(self, check_data):
        """
        判断键值对是否一致
        检查json类型的响应body中是否包含一个或多个键值对
        :param check_data:检查数据字符串
        :return:都包含则返回True； 有一个不包含就返回False
        """
        check_data = json.load(check_data)
        result = []
        for check_key in check_data.items():
            if check_key in self.response.json().items():
                result.append(True)
        else:
            result.append(False)
            result.append(check_key)
        if False in result:
            msg = "有键值对不一致,如下:{}".format(result)
            print(msg)
            return False
        else:
            msg = "校验所有键值对成功!"
            print(msg)
            return True

    def response_code_check(self, check_code):
        """判断返回的状态码"""
        if self.response.status_code == int(check_code):
            msg = "返回状态码:{}".format(check_code)
            print(msg)
            return True
        else:
            return False



if __name__ =='__main__':
    response = APIRun('test_apply_join.yaml','market',2).test_run()
    print(response)
    a = AssertCheck(response)
    a.json_check_key("errorno,aabc")
    check_data = '{"errorno": "2324", "tips_type": 1, "tips_title": "", "errormsg": "入群申请已提交，请耐心等待群主审批。"}'
    a.key_value_check(check_data)
    a.response_code_check(200)
